package com.xxkk.spring_boot_web.service;

import com.alibaba.fastjson.JSONObject;
import com.xxkk.spring_boot_web.sdk.TPRequestUtil;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author xxkk
 * @version 1.0.0
 * @title RechargeGameCoin
 * @description ʕ•ᴥ•ʔ
 * @create 2024/10/19 17:31
 **/
public class RechargeGameCoin {
    private final static Logger logger = Logger.getLogger(RechargeGameCoin.class);

    /**
     * 向java游戏服务器发起请求 在玩家充值交易完成之后为玩家充值游戏币
     *
     * @param url        服务请求地址接口
     * @param map        请求参数
     * @param privateKey 通讯加密私钥
     * @return 游戏服务器响应信息
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static String recharge(String url, Map<String, Object> map, String privateKey) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        Map<String, Object> params = new TreeMap<>(map);
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet())
            sb.append(params.get(key));  // 拼接参数
        String keyStr = sb.toString();  // 得到待加密的字符串
        System.out.println("请求java服务器加分操作:" + keyStr);
        String signedStr = TPRequestUtil.privateEncrypt(keyStr, TPRequestUtil.getPrivateKey(privateKey));  // 私钥加密
        params.put("sign", signedStr);
        String jsonString = JSONObject.toJSONString(params);
        return TPRequestUtil.doPost(url, jsonString);
    }
}
